﻿(function (Topro) {
    //UI命名空间
    var Util = Topro.Util || {};

    /*******************************
    * 重写Ajax
    *******************************/
    Util.Ajax = function (opt) {

        var fn = {
            error: function (XMLHttpRequest, textStatus, errorThrown) { },
            success: function (data, textStatus) { }
        }
        if (opt.error) {
            fn.error = opt.error;
        }
        if (opt.success) {
            fn.success = opt.success;
        }

        var _opt = $.extend(opt, {
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                fn.error(XMLHttpRequest, textStatus, errorThrown);
            },
            success: function (data, textStatus) {
                try {
                    if (data.length < 500) {
                        var dataJson = $.parseJSON(data);
                        if (dataJson.Error) {
                            FlashPay.UI.Alert({ content: dataJson.Message });
                            data = "";
                        }
                    }
                    if (typeof (data) === "object") {
                        if (data.callback != undefined && data.callback != "") {
                            eval(data.callback);
                        }
                    }
                    if (data && data.IsLogout) {
                        eval(data.Callback);
                    }
                } catch (e) {
                }
                fn.success(data, textStatus);
            }
        });

        $.ajax(_opt);


    };

    /*******************************
    * 获取参数
    *******************************/
    Util.GetQueryString = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    /*******************************
    * 把url的参数部分转化成json对象
    *******************************/
    Util.parseQueryString = function (url) {

        var reg_url = /^[^\?]+\?([\w\W]+)$/,
            reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
            arr_url = reg_url.exec(url),
            json = {};
        if (arr_url && arr_url[1]) {
            var str_para = arr_url[1], result;
            while ((result = reg_para.exec(str_para)) != null) {
                json[result[1]] = result[2];
            }
        }
        return json;
    }

    /*******************************
   * 把url的参数部分转化成json对象,为空不转为对象
   *******************************/
    Util.parseQueryString2 = function (url) {
        var obj = {};
        var keyvalue = [];
        var key = "",
            value = "";
        var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
        for (var i in paraString) {
            keyvalue = paraString[i].split("=");
            key = keyvalue[0];
            value = keyvalue[1];
            if (value != "") {
                obj[key] = value;
            }
        }
        return obj;
    }


    Util.Validator = function (options) {
        var defaults = {
            formObj: null,
            rules: {},
            messages: {}
        };
        // 处理默认参数
        var opts = $.extend({}, defaults, options);

        return opts.formObj.validate({
            ignore: "",
            rules: opts.rules,
            messages: opts.messages,
            errorElement: "em",
            errorPlacement: function (error, element) {
                FlashPay.Util.Tip_popover({
                    element: element,
                    content: error[0].innerText,
                    isShow: true
                });
            },
            success: function (label, element) {
                FlashPay.Util.Tip_popover({
                    element: $(element),
                    isShow: false
                });
            }
        });
    };


    Util.SetInputVal = function (name, value) {
        $("input[name=" + name + "]").val(value);
    };


    Util.SetLabelHtml = function (name, value) {
        $("#" + name).html(value);
    };

    //验证是否为空
    Util.isNullOrEmptySpance = function (value) {
        if (Object.prototype.toString.call(value) === "[object String]") {
            if ((value == null || value.trim() == "" || value == 'undefined' || value == 'null'))
                return true;
        } else {
            if ((value == null || value == "" || value == 'undefined' || value == 'null'))
                return true;
        }
        return false;
    };

    //验证是否为URL
    Util.IsURL = function (str_url) {
        var str = str_url;
        var Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
        var objExp = new RegExp(Expression);
        if (objExp.test(str) == true) {
            return true;
        } else {
            return false;
        }
    };

    Util.Tip_popover = function (options) {
        var defaults = {
            element: null,
            content: "",
            isShow: false
        };

        // 处理默认参数
        var opts = $.extend({}, defaults, options);

        if (opts.element == null) {
            return;
        }
        if (opts.isShow && FlashPay.Util.isNullOrEmptySpance(opts.content)) {
            return;
        }
        var objSpan = opts.element.next("div")[0];
        if (opts.isShow && !opts.element.parent().hasClass("has-error")) {
            opts.element.parent().addClass("has-error has-feedback");

            if (!objSpan) {
                objSpan = $("<div class=\"popoverDiv\" data-placement=\"bottom\" href=\"javascript:void(0);\"></div>");
                objSpan.insertAfter(opts.element);
                objSpan.popover();
            }

            $(objSpan).attr('data-container', 'body');
            $(objSpan).attr('data-toggle', 'popover');
            $(objSpan).attr('data-placement', 'bottom');
            $(objSpan).attr('data-content', opts.content);

            objSpan.click();
        }

        if (!opts.isShow && objSpan) {
            objSpan.click();

            opts.element.parent().removeClass("has-error has-feedback");
            objSpan.remove();
        }
    };

    //显示状态值
    Util.GetStatusValue = function (status) {
        if (FlashPay.Util.isNullOrEmptySpance(status)) return "";
        switch (status) {
            case 1:
                return "<span class=\"green bold\">启用</span>";
                break;
            case 2:
                return "<span class=\"red bold\">禁用</span>";
                break;
            case 3:
                return "<span class=\"red bold\">删除</span>";
                break;
        }
        return "";
    };

    //显示状态值
    Util.NoticeStatusStyle = function (status) {
        if (FlashPay.Util.isNullOrEmptySpance(status)) return "";
        switch (status) {
            case 1:
                return "<span>未通知</span>";
                break;
            case 2:
                return "<span class=\"green bold\">通知成功</span>";
                break;
            case 3:
                return "<span class=\"red bold\">通知失败</span>";
                break;
            case 4:
                return "<span class=\"orange bold\">通知中</span>";
                break;
        }
        return "";
    };

    //split分割字符串，且只取出第一个 
    Util.SplitFirstValue = function (thisVal) {
        if (FlashPay.Util.isNullOrEmptySpance(thisVal)) return "";
        let arr = thisVal.split(",");
        return arr[0];
    };

    //角色显示状态值
    Util.GetRoleStatusValue = function (status) {
        if (FlashPay.Util.isNullOrEmptySpance(status)) return "";
        switch (status) {
            case 1:
                return "显示";
                break;
            case 2:
                return "隐藏";
                break;
        }
        return "";
    };

    //银行卡类型
    Util.GetCardTypeValue = function (CardType) {
        if (FlashPay.Util.isNullOrEmptySpance(CardType)) return "";
        switch (CardType) {
            case 1:
                return "收款卡";
                break;
            case 2:
                return "中转卡";
                break;
            case 3:
                return "付款卡";
                break;
            case 4:
                return "备用卡";
                break;
            case 5:
                return "储备卡";
                break;
            case 6:
                return "下发储备卡";
                break;
            case 7:
                return "付款储备卡";
                break;
            case 99:
                return "作废卡";
                break;
        }
        return "";
    };

    //银行卡类型
    Util.GetAdjustStatusValue = function (CardType) {
        if (FlashPay.Util.isNullOrEmptySpance(CardType)) return "";
        switch (CardType) {
            case 1:
                return "收款";
                break;
            case 2:
                return "付款";
                break;
            case 3:
                return "中转";
                break;
        }
        return "";
    };

    //跨行转账
    Util.GetCrossBankPayValue = function (CrossBankPay) {
        if (FlashPay.Util.isNullOrEmptySpance(CrossBankPay)) return "";
        switch (CrossBankPay) {
            case 1:
                return "同行";
                break;
            case 2:
                return "跨行";
                break;
            case 3:
                return "全部";
                break;
        }
        return "";
    };

    //银行卡号截取显示
    Util.SubCardNumber = function (CardNumber) {
        if (Util.isNullOrEmptySpance(CardNumber)) return "";
        var StaNum = CardNumber.substring(0, 4);
        var EndNum = CardNumber.substr(CardNumber.length - 4);
        return StaNum + "***********" + EndNum;
    };

    //付款区间起迄
    Util.ViewPaymentSE = function (PaymentStart, PaymentEnd) {
        var StaNum = PaymentStart;
        var EndNum = PaymentEnd;
        return "EX" + StaNum + "-" + EndNum;
    };

    //当前平台:卡管后台: 1,秒付宝存款: 2,秒付宝付款: 3
    Util.Platform = function () {
        return 1;
    };

    //银行卡使用状态
    Util.GetCardStatusValue = function (CardStatus) {
        if (FlashPay.Util.isNullOrEmptySpance(CardStatus)) return "";
        switch (CardStatus) {
            case 1:
                return "有效";
                break;
            case 2:
                return "冻结";
                break;
        }
        return "";
    };

    //银行卡启用状态
    Util.GetCardEnableStatusValue = function (CardEnableStatus) {
        if (FlashPay.Util.isNullOrEmptySpance(CardEnableStatus)) return "";
        switch (CardEnableStatus) {
            case 1:
                return " <span class='green bold'>启用</span> ";
                break;
            case 2:
                return " <span class='red bold'>禁用</span> ";
                break;
            case 3:
                return "删除";
                break;
            case 4:
                return " <span class='#1C1C1C bold'>未授权</span> ";
                break;
        }
        return "";
    };

    //库存卡启用状态
    Util.GetSpareCardEnableStatusValue = function (CardEnableStatus) {
        if (FlashPay.Util.isNullOrEmptySpance(CardEnableStatus)) return "";
        switch (CardEnableStatus) {
            case 1:
                return " <span class='green bold'>启用</span> ";
                break;
            case 2:
                return " <span class='red bold'>禁用</span> ";
                break;
            case 3:
                return "删除";
                break;
            case 4:
                return " <span class='red bold'>未授权</span> ";
                break;
        }
        return "";
    };

    //通知状态
    Util.GetNoticeStatusValue = function (noticeStatus) {
        if (FlashPay.Util.isNullOrEmptySpance(noticeStatus)) return "";
        switch (noticeStatus) {
            case 1:
                return " <span class='green bold'>未通知</span> ";
                break;
            case 2:
                return " <span class='green bold'>通知成功</span> ";
                break;
            case 3:
                return "<span class='green bold'>通知失败</span> ";
                break;
            case 4:
                return " <span class='red bold'>通知中</span> ";
                break;
        }
        return "";
    }
    //通知状态
    Util.GetPaymentStatusValue = function (paymentStatus) {
        if (FlashPay.Util.isNullOrEmptySpance(paymentStatus)) return "";
        switch (paymentStatus) {
            case 1:
                return " <span class='green bold'>未付款</span> 取消";
                break;
            case 2:
                return " <span class='green bold'>付款成功</span> ";
                break;
            case 3:
                return "<span class='green bold'>付款失败</span> ";
                break;
            case 4:
                return " <span class='red bold'>付款中</span> 查询";
                break;
            case 4:
                return " <span class='red bold'>取消付款</span> ";
                break;
        }
        return "";
    };

    //接口类型
    Util.GetApiPushType = function (type) {
        switch (type) {
            case 1:
                return " <span class='orange bold'>存款(主)</span> ";
                break;
            case 2:
                return " <span class='yellow bold'>存款(副)</span> ";
                break;
            case 3:
                return "<span class='bold'>付款(主)</span> ";
                break;
            case 4:
                return " <span class='red bold'>付款(副)</span> ";
                break;
            case 5:
                return "<span class='bold'>中转(主)</span> ";
                break;
            case 6:
                return " <span class='red bold'>中转(副)</span> ";
                break;
        }
        return "";
    };

    //将时间截取成日期
    Util.GetDateByTime = function (time, type = 0) {
        if (time == null || time == "null" || time == undefined) return "";
        time = time.replace("T", " ").replace("1970-01-01 00:00:00", " ");
        if (type != 0) return time;
        return time.substr(0, 10);
    };

    //获取时间差(分钟数)
    Util.TimeDiff = function (d1) {
        if (d1 == null || d1 * 1 == 0) {
            return 0;
        }
        d1 = d1.replace("T", " ").replace("0001-01-01", " ");

        var dateBegin = new Date(d1.replace(/-/g, "/"));//将-转化为/，使用new Date
        var dateEnd = new Date();//获取当前时间
        var dateDiff = dateEnd.getTime() - dateBegin.getTime();//时间差的毫秒数
        var leave1 = dateDiff % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000))//计算出小时数
        var leave2 = leave1 % (3600 * 1000)    //计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000))//计算相差分钟数
        return hours * 60 + minutes;
    };

    //时间格式化
    //Util.FormatDate = function (date, fmt = 'yyyy-MM-DD hh:mm:ss') {
    //    if (date == null || date == "null") {
    //        return "";
    //    }
    //    date = date.replace("T", " ").replace("0001-01-01", " ");
    //    date = new Date(date); 
    //    var o = {
    //        "M+": date.getMonth() + 1,//月份
    //        "D+": date.getDay(),//日
    //        "h+": date.getHours(),//hours
    //        "m+": date.getMinutes(),//分钟
    //        's+': date.getSeconds(),//秒,
    //    }
    //    if (/(y+)/.test(fmt)) {
    //        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    //    }
    //    for (var k in o) {
    //        if (new RegExp("(" + k + ")").test(fmt)) {
    //            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
    //        }
    //    }
    //    return fmt;
    //}
    Util.FormatDate = function (date, fmt = 'yyyy-MM-DD hh:mm:ss') {
        if (date == null || date == "null") {
            return "";
        }
        date = date.replace("T", " ").replace("0001-01-01", " ");
        return date.substr(0, 19);
    };

    //获取xx天后的日期
    Util.GetDateStr = function (AddDayCount) {
        var dd = new Date();
        dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期
        var y = dd.getFullYear();
        var m = dd.getMonth() + 1;//获取当前月份的日期
        var d = dd.getDate();
        return y + "-" + (m < 10 ? '0' + m : m) + "-" + (d < 10 ? '0' + d : d);
    };

    //截取字符串加上...
    Util.GetShortStr = function (str, len = 20) {
        if (Util.isNullOrEmptySpance(str)) return "";
        if (str.length > len) {
            return str.substr(0, len) + "...";
        } else {
            return str.substr(0, len);
        }
    };

    Util.FormatNumber = function (num, precision, separator) {
        var parts;
        // 判断是否为数字
        if (!isNaN(parseFloat(num)) && isFinite(num)) {
            num = Number(num);
            // 处理小数点位数
            num = (typeof precision !== 'undefined' ? num.toFixed(precision) : num).toString();
            // 分离数字的小数部分和整数部分
            parts = num.split('.');
            // 整数部分加[separator]分隔, 借用一个著名的正则表达式
            parts[0] = parts[0].toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + (separator || ','));

            return parts.join('.');
        }
        return "0.00";
    };

    Util.Language = function () {

        var language = $.cookie('language');

        if (!FlashPay.Util.isNullOrEmptySpance(language) && language=='en') {
            /* 設定一開始以哪個語系呈現 */
            $.i18n.setLocale("en");

            /* 根據使用者目前語系更改文字內容，動態載入語系檔 */
            $._.replaceByLocale("/js/language/" + $._.getLocale() + ".json");
        }

        return language;
    };

    //导入到全局FlashPay中
    Topro.Util = Util;

})(Topro);